const jwt = require('koa-jwt')
const _ = require('lodash')

const {User, Invitation} = require('../models')
const mailUtils = require('../lib/mail')

module.exports = function (router) {
  router.get('/c/init', function * () {
    let user = yield User.findOne({username: 'harrie'}).exec()

    if (!user) {
      user = yield User.create({
        username: 'harrie',
        password: this.utils.md5('111111'),
        email: 'varharrie@gmail.com'
      })
    }

    this.body = this.apiSuccess({user})
  })

  // 登录认证
  router.post('/c/auth', function * () {
    this.checkBody('username').notEmpty('请输入账号。')
    this.checkBody('password').notEmpty('请输入密码。')
    if (this.errors) this.throwError()

    let {username, password} = this.request.body
    let promise = username.indexOf('@') === -1
        ? User.findByUsername(username).exec()
        : User.findByEmail(username).exec()
    let user = yield promise
    if (!user) this.throw('用户名不存在。')
    if (user.password !== this.utils.md5(password)) this.throw('密码错误')

    let token = jwt.sign(_.pick(user, ['_id', 'username']), this.config.app.secret)
    yield user.update({$set: {lastLoginedAt: Date.now()}})

    this.body = this.apiSuccess({token})
  })

  // 受邀注册
  router.post('/c/user', function * () {
    if (!this.config.invitation.enable) this.throw('本站已禁用邀请注册功能。')

    this.checkBody('username').notEmpty('请输入账号。').trim().toLowercase()
    this.checkBody('password').notEmpty('请输入密码。').trim().toLowercase()
    this.checkBody('inviteCode').notEmpty('请输入邀请码。')
    this.checkBody('email').isEmail('请输入正确的电子邮箱。')
    if (this.errors) this.throwError()

    let {username, password, inviteCode: code, email} = this.request.body

    let invitation = yield Invitation.findOne({code, invitee: null}).populate('username').exec()
    if (!invitation) this.throw('无效的邀请码。')

    if (this.config.invitation.limited &&
        !this.config.invitation.user[invitation.inviter.username]) this.throw('本站已禁用邀请注册功能。')

    let user = yield User.findByUsername(username).exec()
    if (user) this.throw('用户名已存在。')

    user = yield User.findOne({email}).exec()
    if (user) this.throw('电子邮箱已注册。')

    user = yield User.create({username, password, email})

    invitation.invitee = user
    invitation.invitedAt = Date.now()
    yield invitation.save()

    let token = jwt.sign(_.pick(user, ['_id', 'username']))

    this.body = this.apiSuccess({token})
  })

  // 发送激活邮件
  router.get('/mail/sendActiveMail', function * () {
    let {_id} = this.state.user
    let user = yield User.findById(_id).exec()

    let code = this.utils.md5(user.username + user.password + user.email + this.config.app.secret)
    mailUtils.sendActiveMail(user.email, user.username, code)

    this.body = this.apiSuccess()
  })

  // 激活账号
  router.get('/c/mail/active', function * () {
    this.checkQuery('code').notEmpty('缺少验证码。')
    this.checkQuery('username').notEmpty('缺少用户名。')
    if (this.errors) this.throwError()

    let {code, username} = this.query.code
    let user = yield User.findByUsername(username)
    if (!user) this.throw('用户不存在。')

    let _code = this.utils.md5(user.username + user.password + user.email + this.config.app.secret)
    if (_code !== code) this.throw('验证码不匹配。')

    user.emailVerified = true
    yield user.save()

    this.body = this.apiSuccess()
  })
}
